const jwt = require('jsonwebtoken');

const createJWT = function ({ payload }) {
   return jwt.sign({ payload }, process.env.JWT_SECRET, {
      expiresIn: process.env.JWT_LIFTTIME,
   });
};

const isTokenValid = ({ token }) => jwt.verify(token, process.env.JWT_SECRET);

const genTokenToCookie = (res, user) => {
   const token = createJWT({ payload: user });
   const oneDay = 1000 * 60 * 60 * 24;

   res.cookie('token', token, {
      httpOnly: true,
      expires: new Date(Date.now() + oneDay), // 过期时间
      secure: process.env.NODE_ENV === 'production',
      signed: true,
   });
   /**
      let cookieString = `token=${token}; Expires=${oneDay}; HttpOnly`;
      if (process.env.NODE_ENV === 'production') {
         cookieString += '; Secure';
      }
      res.setHeader('Set-Cookie', cookieString);
    */
};

module.exports = {
   createJWT,
   isTokenValid,
   genTokenToCookie,
};
